<?php
/**
 * Created by PhpStorm.
 * User: shaowei
 * Date: 2022/8/31
 * Time: 14:18
 */

namespace App\Datas;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Tools\FunTool;

class User
{
    /**
     * 通过google标识获取用户信息
     * @param $google
     * @return array|null
     */
    public function getUserGoogle($google) {
        $userInfo = DB::table('user')->where([
            'google' => $google,
            'delete' => 0
        ])->first();
        if(!$userInfo) {
            return null;
        }
        return (array)$userInfo;
    }

    /**
     * 通过苹果标识获取用户信息
     * @param $google
     * @return array|null
     */
    public function getUserApple($apple) {
        $userInfo = DB::table('user')->where([
            'apple' => $apple,
            'delete' => 0
        ])->first();
        if(!$userInfo) {
            return null;
        }
        return (array)$userInfo;
    }


    /**
     * 通过微信标识获取用户信息
     * @param $google
     * @return array|null
     */
    public function getUserWeixin($weixin) {
        $userInfo = DB::table('user')->where([
            'weixin' => $weixin,
            'delete' => 0
        ])->first();
        if(!$userInfo) {
            return null;
        }
        return (array)$userInfo;
    }

    /**
     * 通过微信小程序标识获取用户信息
     * @param $weixin
     * @return array|null
     */
    public function getUserJSWeixin($weixin) {
        $userInfo = DB::table('user')->where([
            'jsweixin' => $weixin,
            'delete' => 0
        ])->first();
        if(!$userInfo) {
            return null;
        }
        return (array)$userInfo;
    }


    /**
     * 通过QQ标识获取用户信息
     * @param $google
     * @return array|null
     */
    public function getUserQq($qq) {
        $userInfo = DB::table('user')->where([
            'qq' => $qq,
            'delete' => 0
        ])->first();
        if(!$userInfo) {
            return null;
        }
        return (array)$userInfo;
    }

    /**
     * 通过Id标识获取用户信息
     * @param $google
     * @return array|null
     */
    public function getUser($userId) {
        $userInfo = DB::table('user')->where([
            'id' => $userId,
            'delete' => 0
        ])->first();
        if(!$userInfo) {
            return null;
        }
        $data = (array)$userInfo;
        if ($data["is_super_vip"] == 1) {
            $data["vip_exp"] = time() + 60 * 86400;
            $data['rcy_vip_exp'] = time() + 60 * 86400;
        }

        $data['vip_surplus'] = $data['vip_exp'] - time();
        if ($data['vip_surplus'] < 0) {
            $data['vip_surplus'] = 0;
        }
        if ($data['vip_surplus']/(3600*24*365) > 50) {
            $data['vip_surplus'] = -1;
        }

        $data['ecy_vip_surplus'] = $data['rcy_vip_exp'] - time();
        if ($data['ecy_vip_surplus'] < 0) {
            $data['ecy_vip_surplus'] = 0;
        }
        if ($data['ecy_vip_surplus']/(3600*24*365) > 50) {
            $data['ecy_vip_surplus'] = -1;
        }
        if ($data["is_super_vip"] == 1) {
            $data["vip_surplus"] = -1;
            $data['ecy_vip_surplus'] = -1;
        }

        return $data;
    }


    /**
     * 创建用户
     * @param $nickname
     * @param $phone
     * @param $google
     * @param $apple
     * @param $weixin
     * @param $jsweixin
     * @param $qq
     * @param $image
     * @param $isedit
     * @return int
     */
    public function addUser($nickname, $phone, $google, $apple, $weixin, $jsweixin, $qq, $deviceId, $image = "", $isedit = 1,$channel = "", $email = '') {
        if (empty($nickname)) {
            $nickname = 'Dall-' . substr(md5(time()), 0, 6);
        }

        if ($image == '') {
            $image = env('APP_FILES_URL') . '/user/default.png';
            if ($_SERVER['HTTP_AIPKG'] ?? '' == 'com.xdx.dreamcatcher') {
                $image = env('APP_FILES_URL') . '/user/default-1.png';
            }
        }
        return DB::table('user')->insertGetId([
            'nickname' => $nickname,
            'phone' => $phone,
            'google' => $google,
            'apple' => $apple,
            'weixin' => $weixin,
            'jsweixin' => $jsweixin,
            'qq' => $qq,
            'image' => $image,
            'device_id' => $deviceId,
            'isedit' => $isedit,
            'channel' => $channel,
            'created_at'=>FunTool::getReduceTime(4),
            'email' => $email
        ]);
    }


    /**
     * 设置redis token
     * @param $token
     * @param $userId
     * @return bool
     */
    public function setTokenUserId($token, $userId) {
        $key = 'USER:TOKEN:' . $token;
        Redis::SET($key, $userId);
        Redis::EXPIRE($key, 3600*24*30);
        return true;
    }


    /**
     * 获取redis token
     * @param $token
     * @return mixed
     */
    public function getTokenUserId($token) {
        $key = 'USER:TOKEN:' . $token;
        return Redis::GET($key);
    }


    /**
     * 设置昵称
     * @param $userId
     * @param $nickname
     */
    public function setNickname($userId, $nickname) {
        DB::table('user')
            ->where([
                'id' => $userId
            ])
            ->update([
                'nickname'=>$nickname,
                'isedit'=>0

        ]);
    }

    /**
     * 获取昵称是否存在
     * @param $nickname
     * @return bool
     */
    public function findNickName($nickname) {
        $count = DB::table('user')->where([
            'nickname' => $nickname
        ])->count();
        if ($count > 0) {
            return true;
        }
        return false;
    }

    /**
     * 设置图片
     * @param $userId
     * @param $image
     */
    public function setImage($userId, $image) {
        DB::table('user')
            ->where([
                'id' => $userId
            ])
            ->update([
                'image'=>$image
            ]);
    }


    /**
     * 删除用户
     * @param $userId
     */
    public function delete($userId) {
        DB::table('user')
            ->where([
                'id' => $userId
            ])
            ->update([
                'delete'=>1
            ]);
    }

    /**
     * 更新用户会员时长
     * @param $field 会员数据库字段
     */
    public function updateVipExp($userId, $time, $field) {
        $userData = DB::table('user')->where(['id'=>$userId])->first();
        if(!$userData) {
            return false;
        }
        $userData = (array)$userData;
        $vipExp = $userData[$field];
        $new = time();
        if ($vipExp < $new) {
            $vipExp = $new;
        }

        DB::table('user')->where(['id'=>$userId])->update([$field => $vipExp+$time]);
        return true;
    }

    /**
     * 修改用户剩余点数并写入日志表
     * 当前type类型最高为7，新增+1即可
     */ 
    public function updateDot($userId, $dot, $type = 0) {
        DB::table('user')->where(['id' => $userId])->increment('dot', $dot);

        DB::table('dot_log')->insert([
            'user_id' => $userId,
            'value' => $dot,
            'type' => $type
        ]);
        return true;
    }

    /**
     * 更新用户的AF归因渠道
     * @param $userId
     * @param $channel
     * @return bool
     */
    public function updateChannel($userId, $channel) {
        DB::table('user')->where(['id'=>$userId])->update(["channel" => $channel]);
        return true;
    }

    /**
     * 设置用户日活跃
     * @param $userId
     */
    public function setActive($userId) {
        $key = 'USERACTIVE:' . date('Ymd');
        $has = Redis::SISMEMBER($key, $userId);
        if ($has) {
            return false;
        }

        DB::table('user_active')->insert([
            'user_id' => $userId,
            'day' => intval(date('Ymd'))
        ]);

        Redis::SADD($key, $userId);
        if(Redis::TTL($key) == -1){
            Redis::EXPIRE($key, 24 * 3600);
        }
        return true;
    }


    /**
     * 添加打开日志
     * @param $userId
     * @param $ip
     * @param $deviceId
     */
    public function openLog($userId, $ip, $deviceId) {
        DB::table('user_open_log')->insert([
            'user_id' => $userId,
            'ip' => $ip,
            'device_id' => $deviceId,
            'created_at'=>FunTool::getReduceTime(4)
        ]);
    }

    public function setRemainCount($userId, $count = 1)
    {
        $date = date("ymd");
        $key = 'painter:opus:remaining:'.$date;
        Redis::hincrby($key, $userId, $count);
        if(Redis::TTL($key) == -1){
            Redis::EXPIRE($key, 24 * 3600 * 2);
        }
    }

    public function getRemainCount($userId)
    {
        $date = date("ymd");
        $key = 'painter:opus:remaining:'.$date;
        return Redis::hget($key, $userId) ?? 0;
    }

    public function setDhNum($userId, $dot)
    {
        $key = 'USER:GIVEDOT:'.$userId;
        Redis::hincrby($key, 'dot', $dot);
        if(Redis::TTL($key) == -1){
            Redis::EXPIRE($key, 24 * 3600);
        }
    }

    public function getDhNum($userId)
    {
        $key = 'USER:GIVEDOT:'.$userId;
        $dot = Redis::hget($key, 'dot');
        if ($dot > 0) {
            Redis::del($key);
        }

        return $dot;
    }

    /**
     * 设置图片
     * @param $userId
     * @param $image
     */
    public function setUserPermanent($userId) {
        DB::table('user')->where(['id' => $userId])->update(['is_permanent' => 1]);
    }

    /**
     * 通过设备id获取用户
     * @param $deviceId
     */
    public function getUserByDevice($deviceId) {
        $userInfo = DB::table('user')->where([
            'device_id' => $deviceId,
            'delete' => 0
        ])->orderByDesc('id')->first();
        if(!$userInfo) {
            return null;
            $nickname = 'Dall-' . substr(md5(time()), 0, 6);

            $image = env('APP_FILES_URL') . '/user/default.png';
            if ($_SERVER['HTTP_AIPKG'] ?? '' == 'com.xdx.dreamcatcher') {
                $image = env('APP_FILES_URL') . '/user/default-1.png';
            }
            $userId =  DB::table('user')->insertGetId([
                'nickname' => $nickname,
                'phone' => '',
                'google' => '',
                'apple' => '',
                'weixin' => '',
                'jsweixin' => '',
                'qq' => '',
                'image' => $image,
                'device_id' => $deviceId,
                'isedit' => 0
            ]);

            $userInfo = [
                'id' => $userId,
                'nickname' => $nickname,
                'phone' => '',
                'google' => '',
                'apple' => '',
                'weixin' => '',
                'qq' => '',
                'image' => $image,
                'dot' => 0,
                'vip_exp' => 0
            ];
        }
        return (array)$userInfo;
    }

    public function updateDotData($oldUserId, $newUserId) {
        return DB::table('dot_log')->where(['user_id'=>$oldUserId])->update(['user_id'=>$newUserId]);
    }

    public function updateDotNew($userId, $dot) {
        DB::table('user')->where(['id' => $userId])->increment('dot', $dot);

        return true;
    }

    /**
     * 根据用户id，更新信息
     * @param $id
     * @param $updateFiled
     * @return int
     */
    public function updateById($id, $updateFiled) {
        return DB::table('user')->where(['id'=>$id])->update($updateFiled);
    }


    public function updateNoLoginData($deviceId, $userId, $platform = 0){
        //更新作图记录
        $opus = DB::table('opus')->where(['user_id'=>0, 'device_id'=>$deviceId])->select('id')->get()->toArray();
        if (!empty($opus)) {
            $opusIds = array_column($opus,'id');
            DB::table('opus')->whereIn('id',$opusIds)->update(['user_id'=>$userId]);
        }

    }

    /**
     * 判断是非会员老用户
     */
    public function getIsOldVip($userId, $deviceId){
        $now = date('Y-m-d');
        $deviceInfo = DB::table('system_device')->where('device_id', $deviceId)->where('created_at','like',$now.'%')->first();
        $vip = 0;
        if (!$userId) {
            $account = DB::table('user')->where('device_id',$deviceId)->where('delete',0)->first();
        }else{
            $account = DB::table('user')->where('id',$userId)->where('delete',0)->first();
        }
        if ($account) {
            if ($account->is_super_vip == 1 || strtotime($account->vip_exp) > time() ) {//会员
                $vip = 1;
            }
        }
        if (!$deviceInfo && 0 == $vip) {//不是今天注册的且不是VIP
            return true;
        }else{
            return false;
        }

    }





}